package com.google.incomplete.services.impl;

import java.io.IOException;
import com.google.incomplete.dao.UnitMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.Reader;
import com.google.incomplete.entity.Unit;
import com.google.incomplete.services.UnitService;

public class UnitServiceImpl implements UnitService {

    public static void main(String[] args ) {
        UnitService unitService = new UnitServiceImpl();
        Unit unit = unitService.getUnit("asdf");
        printUnit(unit);
    }
    
    public Unit getUnit(String id) {
        String resource = "mybatis.xml";
        SqlSession session = null;
        try {
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
            session = sqlMapper.openSession();
            UnitMapper mapper = session.getMapper(UnitMapper.class);
            Unit unit = mapper.getUnit(id);
            return unit;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (session !=null ) session.close();
        }


        return null;
    }
    public static void printUnit(Unit unit) {
        if (unit == null ) {
            System.out.println("unit is null");
            return ;
        }
        System.out.println("unitname is " + unit.getUnitName());
        System.out.println("unitcode is " + unit.getUnitCode());
        System.out.println("telphone is " + unit.getTelphone());
        System.out.println("unitclass is " + unit.getUnitClass());
    }

}
